package com.example.concurrent.demo.threads;

import lombok.extern.slf4j.Slf4j;

/**
 * synchronized使用实例
 * @author liu.nh
 */
@Slf4j
public class SynchronizedDemo implements Runnable {

    private static String threadName;
    private static volatile Object objLock = "objLock";
    private static volatile int count = 10;

    public SynchronizedDemo(String threadName){
        this.threadName = threadName;
    }


    /**
     * 会出现线程安全问题
     */
    private synchronized void subCountA()  {
        log.info(threadName + ": " + count--);
    }
    /**
     * 不会出现线程安全问题
     * 相当与 synchronized(SynchronizedThreadDemo.class){}
     */
    private static synchronized void subCountB()  {
        log.info(threadName + ": " + count--);
    }
    /**
     * 会出现线程安全问题
     */
    private void subCountC()  {
        synchronized(this) {
            log.info(threadName + ": " + count--);
        }
    }
    /**
     * 不会出现线程安全问题
     */
    private void subCountD()  {
        synchronized(SynchronizedDemo.class) {
            log.info(threadName + ": " + count--);
        }
    }
    /**
     * 不会出现线程安全问题
     */
    private void subCountE()  {
        synchronized(objLock) {
            log.info(threadName + ": " + count--);
        }
    }

    @Override
    public void run() {
        //subCountA();
        //subCountB();
        //subCountC();
        //subCountD();
        subCountE();
    }
}
